package main

import (
	"fmt"
)

/*
替换空格
请实现一个函数，把字符串 s 中的每个空格替换成"%20"。

示例 1：
输入：s = "We are happy."
输出："We%20are%20happy."
 */

//方法1：双指针
/*
func replaceSpace(s string) string {
	b := []byte(s)
	length := len(b)
	spaceCount := 0
	// 计算空格数量
	for _, v := range b {
		if v == ' ' {
			spaceCount++
		}
	}
	// 扩展原有切片
	resizeCount := spaceCount * 2
	tmp := make([]byte, resizeCount)
	b = append(b, tmp...)
	i := length - 1
	j := len(b) - 1
	for i >= 0 {
		if b[i] != ' ' {
			b[j] = b[i]
			i--
			j--
		} else {
			b[j] = '0'
			b[j-1] = '2'
			b[j-2] = '%'
			i--
			j = j - 3
		}
	}
	return string(b)
}

 */

//方法2：直接使用go自带的函数进行替换
/*
func replaceSpace(s string) string {
   s = strings.Replace(s," ","%20",-1)
   return s
}
 */

//暴力解法
func replaceSpace(s string) string {
	b := []byte(s)
	var res string
	for _,j := range b{
		if j != ' '{
			res = res + string(j)
		}else{
			res = res + "%20"
		}
	}
	return res
}

func main() {
	s := "We are happy."
	fmt.Println(replaceSpace(s))
}
